package edu.demo.recommend.advice;

import edu.demo.recommend.common.R;
import edu.demo.recommend.common.ResultCodeEnum;
import edu.demo.recommend.controller.admin.AdminManagerController;
import edu.demo.recommend.exception.RecommendBusinessException;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Objects;

/**
 * 对Controller的切面类
 * @author hb
 */
@Aspect
@Configuration //可以被Spring容器进行管理
public class ControllerAspect {

    @Autowired
    private HttpServletRequest request;
    @Autowired
    private HttpServletResponse response;

    /**
     * 配置切入点
     * @return
     */
    @Around("execution(* edu.demo.recommend.controller.admin.*.*(..)) " +
            "&& @annotation(org.springframework.web.bind.annotation.RequestMapping)")
    public Object adminControllerBeforeValedation(ProceedingJoinPoint joinPoint)throws Throwable{
         //获得方法签名
        Method targetMethod = ((MethodSignature) joinPoint.getSignature()).getMethod();
        //是否存在AdminPermission的注解
        AdminPermission adminPermission = targetMethod.getAnnotation(AdminPermission.class);
        //如果adminPermission为null，表示无需权限校验
        if(Objects.isNull(adminPermission)){
            //执行目标方法
            Object result = joinPoint.proceed();
            return result;
        }
        //需要进行权限校验：判断session中是否存储值
        Object email = request.getSession().getAttribute(AdminManagerController.ADMIN_NAME_SESSION);
        //如果没有登录
        if(Objects.isNull(email)){
            if("text/html".equals(adminPermission.produceType())){
                //跳转到登录页面
                response.sendRedirect("/admin/admin/loginPage");
                return null;
            }else{
                RecommendBusinessException ex = new RecommendBusinessException(ResultCodeEnum.ADMIN_SHOULD_LOGIN);
                return R.setResult(ResultCodeEnum.ADMIN_SHOULD_LOGIN);
            }

        }else{
            //执行目标方法
            Object result = joinPoint.proceed();
            return result;
        }


    }

}
